<?php


class StaffService extends TP_Service {
    private $role;
    public function __construct() {
        parent::__construct();
        $this->load->model("SModel/Staff_model");
        $this->load->model("PModel/V_admin_model");
        $this->load->model("PModel/AccRole_model");
        $this->load->service("PService/AccountService");
        $this->load->service("PService/UploadService");
        $this->load->service("PService/ExportExcelService");
        $this->role = $this->getRole($_SESSION[SESS_UUID]);
    }


    // 能否操作
    private function hasPre() {
        if ($this->role->role_id != WebRole::Manage[TPEnum::Value]) {
            exit(retJson(ErrCode::ErrCode_10404));
        }
    }



    /**
     * 方法名 staffList
     *
     * @Name 获取方法列和角色方法列
     * @Desc 员工列表
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一e
     * @return      [type]                   [description]
     */
    public function staffList($param, $export = false) {
        if (!$export) {
            $param = array_filter($param, 'filtrfunction');
            if (!isset($param['pageNo'], $param['pageSize'])) {
                exit(retJson(ErrCode::ErrCode_10002));
            }

            $conarr['pageNo'] = $param['pageNo'];
            $conarr['pageSize'] = $param['pageSize'];
        }

        $conarr['items']   = "a.id, head_img, usercode, username, email, mobile, department, organization, position, valid, role_id, role_name, ascription, ascription_name,password, uuid,manager,manager_name";
        $conarr['join']    = array("tp_v_admin a", 'tp_staff.aid = a.id');
        $conarr['where']   = sql_format("role_id != '{0}'", WebRole::Manage[TPEnum::Value]);
        $conarr['orderby'] = "id asc";


        // 筛选
        if (isset($param['valid'])) {
            $conarr['where'] .= sql_format(" AND valid = '{0}'", $param['valid']);
        }


        if(isset($param['input']) && !empty($param['input'])){
            $conarr['where'] .= sql_format(" AND ( usercode like '%{0}%' OR  username like '%{0}%' OR email like '%{0}%' )", $param['input']);
        }


        if ($export) {
            $list = $this->Staff_model->get_list_full($conarr);
        } else {
            $list = $this->Staff_model->get_page_list($conarr);
            foreach ($list['ret'] as &$value) {
                $value['validInfo'] = $value['valid'] == EnableState::Enable[TPEnum::Value] ? "已启用" : "已停用";
            }
        }
        return $list;
    }




    /**
     * 方法名 staffEdit
     *
     * @Name 获取方法列和角色方法列
     * @Desc 员工修改
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     *
     */
    public function staffEdit($param) {
        if (!isset(
            $param['usercode'],
            $param['username'],
            $param['password'],
            $param['email'],
            $param['mobile'],
            $param['department'],
            $param['organization'],
            $param['position'],
            $param['valid'],
            $param['role_id'],
          
        )) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $this->hasPre();

        if (!filter_var($param['email'], FILTER_VALIDATE_EMAIL)) {
            exit(retJson(ErrCode::ErrCode_10504));
        }
        if (!validMobile($param['mobile'])) {
            exit(retJson(ErrCode::ErrCode_10505));
        }



        if (empty($param['id'])) {
            // 新增账户
            $p = ['usercode' => $param['usercode'], 'username' => $param['username'], 'role_id' => [$param['role_id']],'email' => $param['email'], 'uuid' => '','password' => $param['password']];
            $param['id'] = $this->AccountService->saveAdminInfo($p);

            $this->Staff_model->add(['aid' => $param['id']]);
        } else {
            if (!isset($param['uuid'])) {
                exit(retJson(ErrCode::ErrCode_10002));
            }


            $salt = md5(GetRandStr(16));
            $password = getPasswrodWithTwiceEncode($param['password'],$salt);
            $params=array(
                'password'=>$password,
                'passsalt'=>$salt,
            );
            $this->Account_model->update($params,['uuid' => $param['uuid']]);


            $this->AccRole_model->update(['role_id' => $param['role_id']], ['uuid' => $param['uuid']]);



            if($param['valid'] == 0){
                $conarr['join'] = array("tp_order o","o.creator = tp_account.uuid","innner");
                $conarr['where'] = sql_format("tp_account.uuid = '{0}'",$param['uuid']);
                
//                $order = $this->Account_model->get_single_full($conarr);
//                if($order){
//                    exit(retJson(ErrCode::ErrCode_10906));
//                }
            }


        }


        


       

        $sql = sql_format(
            "UPDATE tp_staff s JOIN tp_account a ON s.aid = a.id SET
                email = '{0}', username = '{1}', mobile = '{2}', department = '{3}', organization = '{4}',
                position = '{5}', valid = '{6}', ascription = '{7}', ascription_name = '{8}',s.password = '{10}',manager = '{11}',manager_name = '{12}'
            WHERE a.id = '{9}'",
            $param['email'],
            $param['username'],
            $param['mobile'],
            $param['department'],
            $param['organization'],
            $param['position'],
            $param['valid'],
            $param['ascription'] ?? '',
            $param['ascription_name'] ?? '',
            $param['id'],
            $param['password'],
            $param['manager'] ?? '',
            $param['manager_name'] ?? '',

        );
        $this->Staff_model->execute($sql);
        return true;
    }




    /**
     * 方法名 staffImport
     *
     * @Name dealStock
     * @Desc 员工导入
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2022-02-17 14:11:28
     * @return      [type]                   [description]
     */
    public function staffImport() {
        $this->hasPre();

        if (empty($_FILES)) {
            exit(retJson(ErrCode::ErrCode_10601));
        }


        $path = $this->UploadService->UploadFile('staff', true);
        $excellist =  $this->ExportExcelService->importexcel($path, 'K', 'A', 2);
        if (count($excellist) == 0) {
            exit(retJson(ErrCode::ErrCode_10602));
        }

        //去掉空数组
        foreach ($excellist as &$value) {
            $value = array_filter($value, 'filtrfunction');
        }
        $excellist = array_filter($excellist);


        foreach ($excellist as $v) {
            $ascription = '';
            $ascription_name = '';
            if ($v['H'] == "业务员") {
                $role = WebRole::Salesman[TPEnum::Value];
                $ascr = $this->searchAscription(['role' => WebRole::BusinessS[TPEnum::Value], 'username' => $v['I']]);
                if (count($ascr) == 1) {
                    $ascription = $ascr[0]['id'];
                    $ascription_name = $ascr[0]['username'];
                }

                $ma = $this->searchAscription(['role' => WebRole::manager[TPEnum::Value], 'username' => $v['J']]);
                if (count($ma) == 1) {
                    $manager = $ma[0]['id'];
                    $manager_name = $ma[0]['username'];
                }
            } elseif($v['H'] == "业务组长") {
                $role = WebRole::BusinessS[TPEnum::Value];
            }else{
                $role = WebRole::manager[TPEnum::Value];
            }

            // $role = $v['H'] == "业务员" ? WebRole::Salesman[TPEnum::Value] : WebRole::BusinessS[TPEnum::Value];
            $p = ['usercode' => $v['A'], 'username' =>  $v['B'], 'role_id' => [$role],'email' => $v['C'], 'uuid' => '','password' => $v['K']];
            $aid = $this->AccountService->saveAdminInfo($p);
            $this->Staff_model->add(['aid' => $aid]);

            $sql = sql_format(
                "UPDATE tp_staff s JOIN tp_account a ON s.aid = a.id SET
                    email = '{0}', mobile = '{1}', department = '{2}', organization = '{3}',
                    position = '{4}', ascription = '{5}', ascription_name = '{6}',manager = '{8}',manager_name = '{9}',s.password = '{10}'
                WHERE a.id = '{7}'",
                $v['C'],
                $v['D'],
                $v['E'],
                $v['F'],
                $v['G'],
                $ascription ?? "",
                $ascription_name ,
                $aid,
                $manager ?? "",
                $manager_name ?? "",
                $v['K']
            );
            $this->Staff_model->execute($sql);
        }
        return true;
    }




    /**
     * 方法名 staffDelete
     *
     * @Name 获取方法列和角色方法列
     * @Desc 员工删除
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     */
    public function  staffDelete($param) {
        $this->hasPre();

        if (!isset($param['aid']) || empty($param['aid'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $conarr['join'] = array("tp_order o","o.creator = tp_account.uuid");
        $conarr['where'] = sql_format("tp_account.id = '{0}'",$param['aid']);
        
        $order = $this->Account_model->get_single_full($conarr);

        if($order){
            exit(retJson(ErrCode::ErrCode_10906));
        }


        $this->Staff_model->delete(['aid' => $param['aid']]);
        $this->Account_model->delete(['id' => $param['aid']]);
        return true;
    }




    /**
     * 方法名 searchAscription
     *
     * @Name 获取方法列和角色方法列
     * @Desc 查找归属
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一e
     * @return      [type]                   [description]
     */
    public function searchAscription($param) {
        // $param = array_filter($param, 'filtrfunction');
        if (!isset($param['role'], $param['username'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }


        $conarr['items'] = "id, username";
        $conarr['where'] = sql_format("role_id = '{0}'", $param['role']);
        if(!empty($param['username'])){
            $conarr['where'] .= sql_format("and  username like '%{0}%'", $param['username']);
        }
        $list = $this->V_admin_model->get_list_full($conarr);
        return $list;
    }




}
